/**
 * The Free Gaming System; proxy communication management.
 *
 * Copyright 2006 the Free Gaming System developers.
 *
 * FGS is the legal property of its developers, whose names are too
 * numerous to list here.  Please refer to the COPYRIGHT file
 * distributed with this source distribution.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <assert.h>

#include "fgs_game.h"
#include "fgs_internal.h"

static fgs_error_t
connect_proxy(fgs_ctx_t *ctx)
{
  struct sockaddr_in proxy;
  int ret;
  assert(ctx != NULL);

  ctx->proxy_fd = socket(PF_INET, SOCK_STREAM, 0);
  if (ctx->proxy_fd == -1)
    return FGS_ERR_PROXY_UNREACHABLE;

  proxy.sin_family = AF_INET;
  proxy.sin_port = htons(6567);
  proxy.sin_addr.s_addr = inet_addr("127.0.0.1");
  memset(&(proxy.sin_zero), '\0', 8);

  ret = connect(ctx->proxy_fd, (struct sockaddr*)&proxy,
                sizeof(struct sockaddr));
  if (ret == -1)
    {
      ctx->proxy_fd = -1;
      return FGS_ERR_PROXY_UNREACHABLE;
    }

  return FGS_OK;
}

static fgs_error_t
check_proxy_reply(fgs__socket_reply_t *reply, fgs_bool_t *res)
{
  assert(reply != NULL);

  if (strcmp(reply->result, "OK") == 0)
    {
      *res = FGS_TRUE;
      return FGS_OK;
    }
  else if (strcmp(reply->result, "ERROR") == 0)
    {
      *res = FGS_FALSE;
      return FGS_OK;
    }
  else
    {
      fgs__socket_free_reply(reply, FGS_TRUE);
      return FGS_ERR_MALFORMED_REPLY;
    }
}

fgs_error_t
fgs__proxy_connect(fgs_ctx_t *ctx, const char *name,
                   const char *version, int server_port)
{
  fgs__socket_reply_t *rep;
  fgs_baton_t fdb;
  fgs_bool_t result;
  assert(ctx != NULL && name != NULL && version != NULL && server_port > 0);

  FGS_ERR(connect_proxy(ctx));

  /* Send the registration command */
  fdb = (fgs_baton_t)ctx->proxy_fd;
  FGS_ERR(fgs__socket_send(fdb, fgs__callbacks_tcp_send, "REGISTERSERVER",
                           "ssi", name, version, server_port));
  FGS_ERR(fgs__socket_recv(fdb, fgs__callbacks_tcp_recv, &rep));
  FGS_ERR(check_proxy_reply(rep, &result));
  FGS_ERR(fgs__socket_free_reply(rep, FGS_TRUE));

  if (result == FGS_FALSE)
    return FGS_ERR_REGISTRATION_FAILED;

  return FGS_OK;
}


fgs_error_t
fgs__proxy_disconnect(fgs_ctx_t *ctx)
{
  fgs__socket_reply_t *rep;
  fgs_baton_t fdb;
  assert(ctx != NULL);

  fdb = (fgs_baton_t)ctx->proxy_fd;
  FGS_ERR(fgs__socket_send(fdb, fgs__callbacks_tcp_send, "UNREGISTERSERVER", ""));
  FGS_ERR(fgs__socket_recv(fdb, fgs__callbacks_tcp_recv, &rep));
  FGS_ERR(fgs__socket_free_reply(rep, FGS_TRUE));

  shutdown(ctx->proxy_fd, SHUT_RDWR);

  return FGS_OK;
}

fgs_error_t
fgs__proxy_get_config(fgs_ctx_t *ctx, char **key, char **value)
{
  fgs__socket_reply_t *rep;
  fgs_baton_t fdb = (fgs_baton_t)ctx->proxy_fd;
  fgs_bool_t result;
  assert(ctx != NULL && ctx->cb_table->append_config != NULL &&
         key != NULL && value != NULL);


  FGS_ERR(fgs__socket_send(fdb, fgs__callbacks_tcp_send, "GETCONFIG", ""));
  FGS_ERR(fgs__socket_recv(fdb, fgs__callbacks_tcp_recv, &rep));
  FGS_ERR(check_proxy_reply(rep, &result));

  if (result == FGS_FALSE)
    return FGS_ERR_CONFIG_PROCESS;

  /* The final reply has no values. */
  if (rep->argc == 0)
    {
      fgs__socket_free_reply(rep, FGS_TRUE);
      *key = NULL;
      *value = NULL;
      return FGS_OK;
    }
  else if (rep->argc == 2)
    {
      *key = rep->argv[0];
      *value = rep->argv[1];
      fgs__socket_free_reply(rep, FGS_FALSE);
      return FGS_OK;
    }
  else
    {
      fgs__socket_free_reply(rep, FGS_TRUE);
      return FGS_ERR_CONFIG_PROCESS;
    }

  return FGS_OK;
}


fgs_error_t
fgs__proxy_new_client(fgs_ctx_t *ctx, fgs_uuid_t *uuid, char *login,
                      char *passwd_hash, char *nonce)
{
  fgs_baton_t fdb = (fgs_baton_t)ctx->proxy_fd;
  fgs__socket_reply_t *rep;
  fgs_bool_t rep_ok;
  assert(ctx != NULL);

  if (login != NULL)
    {
      /* Try to authenticate with the proxy. */
      FGS_ERR(fgs__socket_send(fdb, fgs__callbacks_tcp_send,
                               "AUTHPLAYERJOIN", "sss", login, passwd_hash,
                               nonce));
    }
  else
    {
      /* Try to authenticate with the proxy. */
      FGS_ERR(fgs__socket_send(fdb, fgs__callbacks_tcp_send,
                               "ANONPLAYERJOIN", ""));
    }

  FGS_ERR(fgs__socket_recv(fdb, fgs__callbacks_tcp_recv, &rep));
  FGS_ERR(check_proxy_reply(rep, &rep_ok));
  if (rep_ok == FGS_FALSE)
    {
      FGS_ERR(fgs__socket_free_reply(rep, FGS_TRUE));
      return FGS_ERR_UNAUTHORIZED_PLAYER;
    }
  if (rep->argc != 1)
    return FGS_ERR_MALFORMED_REPLY;

  *uuid = rep->argv[0];

  FGS_ERR(fgs__socket_free_reply(rep, FGS_FALSE));
  return FGS_OK;
}


fgs_error_t
fgs__proxy_del_client(fgs_ctx_t *ctx, fgs_uuid_t uuid)
{
  fgs_baton_t fdb = (fgs_baton_t)ctx->proxy_fd;
  fgs__socket_reply_t *rep;
  fgs_bool_t rep_ok;

  FGS_ERR(fgs__socket_send(fdb, fgs__callbacks_tcp_send,
                           "PLAYERLEAVE", "s", uuid));
  FGS_ERR(fgs__socket_recv(fdb, fgs__callbacks_tcp_recv, &rep));
  FGS_ERR(check_proxy_reply(rep, &rep_ok));
  FGS_ERR(fgs__socket_free_reply(rep, FGS_TRUE));

  return rep_ok ? FGS_OK : FGS_ERR_PLAYER_UNREGISTER_ERROR;
}


fgs_error_t
fgs__proxy_new_match(fgs_ctx_t *ctx, fgs_uuid_t *uuid)
{
  fgs_baton_t fdb = (fgs_baton_t)ctx->proxy_fd;
  fgs__socket_reply_t *rep;
  fgs_bool_t rep_ok;

  FGS_ERR(fgs__socket_send(fdb, fgs__callbacks_tcp_send,
                           "NEWMATCH", ""));
  FGS_ERR(fgs__socket_recv(fdb, fgs__callbacks_tcp_recv, &rep));
  FGS_ERR(check_proxy_reply(rep, &rep_ok));
  if (rep_ok == FGS_FALSE)
    {
      FGS_ERR(fgs__socket_free_reply(rep, FGS_TRUE));
      return FGS_ERR_UNAUTHORIZED_MATCH;
    }
  if (rep->argc != 1)
    return FGS_ERR_MALFORMED_REPLY;

  *uuid = rep->argv[0];

  FGS_ERR(fgs__socket_free_reply(rep, FGS_FALSE));
  return FGS_OK;
}


fgs_error_t
fgs__proxy_del_match(fgs_ctx_t *ctx, fgs_uuid_t uuid)
{
  fgs_baton_t fdb = (fgs_baton_t)ctx->proxy_fd;
  fgs__socket_reply_t *rep;
  fgs_bool_t rep_ok;

  FGS_ERR(fgs__socket_send(fdb, fgs__callbacks_tcp_send,
                           "DELMATCH", "s", uuid));
  FGS_ERR(fgs__socket_recv(fdb, fgs__callbacks_tcp_recv, &rep));
  FGS_ERR(check_proxy_reply(rep, &rep_ok));
  FGS_ERR(fgs__socket_free_reply(rep, FGS_TRUE));

  return rep_ok ? FGS_OK : FGS_ERR_PLAYER_UNREGISTER_ERROR;
}


fgs_error_t
fgs__proxy_update(fgs_ctx_t *ctx, char *update_type, fgs_uuid_t resource_uuid,
                  char *key, enum fgs_value_type value_type, va_list ap)
{
  char type_strings[] = { 'n', 's', 'i', 'f', 'b' };
  char send_string[] = { 's', 's', ' ', '\0' };
  fgs_baton_t fdb = (fgs_baton_t)ctx->proxy_fd;
  fgs__socket_reply_t *rep;
  fgs_bool_t rep_ok;

  send_string[2] = type_strings[value_type];

  switch (value_type)
    {
    case FGS_NIL:
      FGS_ERR(fgs__socket_send(fdb, fgs__callbacks_tcp_send, update_type,
                               send_string, resource_uuid, key));
      break;
    case FGS_STRING:
      FGS_ERR(fgs__socket_send(fdb, fgs__callbacks_tcp_send, update_type,
                               send_string, resource_uuid, key,
                               va_arg(ap, char*)));
      break;
    case FGS_INT:
      FGS_ERR(fgs__socket_send(fdb, fgs__callbacks_tcp_send, update_type,
                               send_string, resource_uuid, key,
                               va_arg(ap, signed long)));
      break;
    case FGS_FLOAT:
      FGS_ERR(fgs__socket_send(fdb, fgs__callbacks_tcp_send, update_type,
                               send_string, resource_uuid, key,
                               va_arg(ap, double)));
      break;
    case FGS_BOOL:
      FGS_ERR(fgs__socket_send(fdb, fgs__callbacks_tcp_send, update_type,
                               send_string, resource_uuid, key,
                               va_arg(ap, fgs_bool_t)));
      break;
    default:
      return FGS_ERR_INVALID_PARAMS;
    }

  FGS_ERR(fgs__socket_recv(fdb, fgs__callbacks_tcp_recv, &rep));
  FGS_ERR(check_proxy_reply(rep, &rep_ok));
  FGS_ERR(fgs__socket_free_reply(rep, FGS_TRUE));

  return rep_ok ? FGS_OK : FGS_ERR_PLAYER_UNREGISTER_ERROR;
}


fgs_error_t
fgs__proxy_add_to_match(fgs_ctx_t *ctx, fgs_uuid_t match_uuid,
                        fgs_uuid_t player_uuid)
{
  fgs_baton_t fdb = (fgs_baton_t)ctx->proxy_fd;
  fgs__socket_reply_t *rep;
  fgs_bool_t rep_ok;

  FGS_ERR(fgs__socket_send(fdb, fgs__callbacks_tcp_send,
                           "JOINMATCH", "ss", match_uuid, player_uuid));
  FGS_ERR(fgs__socket_recv(fdb, fgs__callbacks_tcp_recv, &rep));
  FGS_ERR(check_proxy_reply(rep, &rep_ok));
  FGS_ERR(fgs__socket_free_reply(rep, FGS_TRUE));

  return rep_ok ? FGS_OK : FGS_ERR_UPDATE_ERROR;
}


fgs_error_t
fgs__proxy_del_from_match(fgs_ctx_t *ctx, fgs_uuid_t match_uuid,
                          fgs_uuid_t player_uuid)
{
  fgs_baton_t fdb = (fgs_baton_t)ctx->proxy_fd;
  fgs__socket_reply_t *rep;
  fgs_bool_t rep_ok;

  FGS_ERR(fgs__socket_send(fdb, fgs__callbacks_tcp_send,
                           "LEAVEMATCH", "ss", match_uuid, player_uuid));
  FGS_ERR(fgs__socket_recv(fdb, fgs__callbacks_tcp_recv, &rep));
  FGS_ERR(check_proxy_reply(rep, &rep_ok));
  FGS_ERR(fgs__socket_free_reply(rep, FGS_TRUE));

  return rep_ok ? FGS_OK : FGS_ERR_UPDATE_ERROR;
}


fgs_error_t
fgs__proxy_commit_match(fgs_ctx_t *ctx, fgs_uuid_t match_uuid)
{
  fgs_baton_t fdb = (fgs_baton_t)ctx->proxy_fd;
  fgs__socket_reply_t *rep;
  fgs_bool_t rep_ok;

  if (match_uuid == NULL)
    FGS_ERR(fgs__socket_send(fdb, fgs__callbacks_tcp_send,
                             "COMMITMATCH", ""));
  else
    FGS_ERR(fgs__socket_send(fdb, fgs__callbacks_tcp_send,
                             "COMMITMATCH", "s", match_uuid));

  FGS_ERR(fgs__socket_recv(fdb, fgs__callbacks_tcp_recv, &rep));
  FGS_ERR(check_proxy_reply(rep, &rep_ok));
  FGS_ERR(fgs__socket_free_reply(rep, FGS_TRUE));

  return rep_ok ? FGS_OK : FGS_ERR_UPDATE_ERROR;
}


fgs_error_t
fgs__proxy_commit_player(fgs_ctx_t *ctx, fgs_uuid_t player_uuid)
{
  fgs_baton_t fdb = (fgs_baton_t)ctx->proxy_fd;
  fgs__socket_reply_t *rep;
  fgs_bool_t rep_ok;

  if (player_uuid == NULL)
    FGS_ERR(fgs__socket_send(fdb, fgs__callbacks_tcp_send,
                             "COMMITPLAYER", ""));
  else
    FGS_ERR(fgs__socket_send(fdb, fgs__callbacks_tcp_send,
                             "COMMITPLAYER", "s", player_uuid));

  FGS_ERR(fgs__socket_recv(fdb, fgs__callbacks_tcp_recv, &rep));
  FGS_ERR(check_proxy_reply(rep, &rep_ok));
  FGS_ERR(fgs__socket_free_reply(rep, FGS_TRUE));

  return rep_ok ? FGS_OK : FGS_ERR_UPDATE_ERROR;
}
